package org.sunsys.qa.web.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.sunsys.qa.web.command.QaWebCommand;
import org.sunsys.qa.web.command.reslover.QaWebCommandResolver;
import org.sunsys.qa.web.command.reslover.QaWebCommandResolverImpl;

/**
 * 
 * 	QaFrontController - acts as Front Controller
 *
 *	Service Name should be part of the Http request.
 *	Once Service Name is received from the request, service controller resolver helps to get Service Controller
 *	Once Service Controller is identified, it can be used to serve the request
 */
@WebServlet(description = "Acts as Front Controller", urlPatterns = { "/service/*" } )
public class QaFrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String ACTION = "action";

	private Logger logger = Logger.getLogger(QaFrontController.class.getName());
	private QaWebCommandResolver commandResolver = new QaWebCommandResolverImpl();
	
    /**
     * Default constructor. 
     */
    public QaFrontController() {
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String action = null;
		/* get the requested serviced name */
		action = request.getParameter(ACTION);
		
		Map<String, String[]> map = request.getParameterMap();
		
		System.out.println("parameter names:"+map.keySet());
		
		/* get the Web Command instance */
		QaWebCommand command =  this.commandResolver.getServiceCommand(action);
		
		if(command == null) {
			logger.error("Invalid Action:"+action+" or Command object not pammed to the action");
		}else {
			/* do serve the request */
			command.execute(request, response);
		}
	}
	
}
